import React, { useState, useEffect } from 'react';
import {
  Modal,
  Transfer,
  Button,
  Space,
  Typography,
  Spin,
  Toast,
  Card,
  Tag,
  Descriptions,
} from '@douyinfe/semi-ui';
import { IconUser, IconUserGroup } from '@douyinfe/semi-icons';
import { roleApi, SysRole } from '../api/role';
import { userApi, SysUser } from '../api/user';

const { Title, Text } = Typography;

interface UserRoleAssignmentProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
  userId: number;
  userName?: string;
}

interface TransferItem {
  label: string;
  value: string;
  key: string;
  disabled?: boolean;
}

const UserRoleAssignment: React.FC<UserRoleAssignmentProps> = ({
  visible,
  onCancel,
  onSuccess,
  userId,
  userName,
}) => {
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [allRoles, setAllRoles] = useState<SysRole[]>([]);
  const [userRoles, setUserRoles] = useState<number[]>([]);
  const [transferData, setTransferData] = useState<TransferItem[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [userInfo, setUserInfo] = useState<SysUser | null>(null);

  useEffect(() => {
    if (visible && userId) {
      loadData();
    }
  }, [visible, userId]);

  const loadData = async () => {
    setLoading(true);
    try {
      const [rolesResponse, userResponse] = await Promise.all([
        roleApi.listAllRoles(),
        userApi.getUserById(userId),
      ]);

      setAllRoles(rolesResponse);
      setUserInfo(userResponse);
      
      // 获取用户当前角色
      const currentRoleIds = userResponse.roleIds || [];
      setUserRoles(currentRoleIds);
      setSelectedKeys(currentRoleIds.map(id => id.toString()));

      // 构建Transfer数据
      const transferItems: TransferItem[] = rolesResponse.map(role => ({
        label: role.roleName,
        value: role.id!.toString(),
        key: role.id!.toString(),
        disabled: role.roleCode === 'SUPER_ADMIN', // 超级管理员角色不可分配
      }));
      setTransferData(transferItems);
    } catch (error) {
      console.error('加载数据失败:', error);
      Toast.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async () => {
    setSubmitting(true);
    try {
      const roleIds = selectedKeys.map(id => parseInt(id)).filter(id => !isNaN(id));
      
      await userApi.assignRoles({
        userId,
        roleIds,
      });
      
      Toast.success('用户角色分配成功');
      onSuccess();
    } catch (error) {
      console.error('角色分配失败:', error);
      Toast.error('角色分配失败');
    } finally {
      setSubmitting(false);
    }
  };

  const getRoleStatus = (roleCode: string) => {
    switch (roleCode) {
      case 'SUPER_ADMIN':
        return <Tag color="red" size="small">超级管理员</Tag>;
      case 'ADMIN':
        return <Tag color="orange" size="small">管理员</Tag>;
      case 'USER':
        return <Tag color="blue" size="small">普通用户</Tag>;
      default:
        return <Tag color="grey" size="small">自定义角色</Tag>;
    }
  };

  const renderSourceItem = (item: TransferItem) => {
    const role = allRoles.find(r => r.id!.toString() === item.key);
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
        <span>{item.label}</span>
        {role && getRoleStatus(role.roleCode)}
      </div>
    );
  };

  const renderSelectedItem = (item: TransferItem) => {
    const role = allRoles.find(r => r.id!.toString() === item.key);
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
        <span>{item.label}</span>
        {role && getRoleStatus(role.roleCode)}
      </div>
    );
  };

  return (
    <Modal
      title={
        <Space>
          <IconUserGroup />
          用户角色分配
        </Space>
      }
      visible={visible}
      onCancel={onCancel}
      width={800}
      height={600}
      footer={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button 
            theme="solid" 
            onClick={handleSubmit}
            loading={submitting}
            disabled={loading}
          >
            确定
          </Button>
        </Space>
      }
    >
      <Spin spinning={loading}>
        {userInfo && (
          <Card style={{ marginBottom: 16 }}>
            <Descriptions data={[
              { key: '用户名', value: userInfo.username },
              { key: '姓名', value: userInfo.realName || '-' },
              { key: '邮箱', value: userInfo.email || '-' },
              { key: '手机号', value: userInfo.mobile || '-' },
              { 
                key: '当前状态', 
                value: userInfo.status === 1 ? 
                  <Tag color="green" size="small">正常</Tag> : 
                  <Tag color="red" size="small">禁用</Tag>
              },
            ]} size="small" />
          </Card>
        )}
        
        <Card>
          <div style={{ marginBottom: 16 }}>
            <Title heading={6}>
              <IconUser style={{ marginRight: 8 }} />
              角色分配
            </Title>
            <Text type="tertiary">
              为用户分配角色，用户将获得所选角色的所有权限。已选择 {selectedKeys.length} 个角色。
            </Text>
          </div>
          
          <Transfer
            style={{ width: '100%' }}
            dataSource={transferData}
            value={selectedKeys}
            onChange={(values) => setSelectedKeys(values as string[])}
            renderSourceItem={renderSourceItem}
            renderSelectedItem={renderSelectedItem}
            inputProps={{
              placeholder: '搜索角色',
            }}
            sourceHeader="可分配角色"
            selectedHeader="已分配角色"
          />
        </Card>
      </Spin>
    </Modal>
  );
};

export default UserRoleAssignment;